var express = require('express');
var router = express.Router();
var dofile = require('../service/file');
var multiparty = require('multiparty');
var fs = require('fs');
var path = require("path");

/* GET home page. */
router.get('/', function (req, res, next) {
    dofile.getAllAlbums(function (err,allAlabums) {
        res.render("index", {
            "albums": allAlabums
        });
    })
});
router.get("/:albumName", function (req, res, next) {
    var albumName = req.params.albumName;
    dofile.getAllImagesByAlbumName(albumName,function (err,imagesArray) {
        if(err){
            next(); //交给下面的中间件
            return;
        }
        res.render("album",{
            "albumname" : albumName,
            "images" : imagesArray
        });
    })
});
router.get("/up", function (req, res, next) {
    dofile.getAllAlbums(function (err,allAlabums) {
        res.render("up", {
            "albums": allAlabums
        });
    })
});
router.post("/up", function (req, res, next) {
    // 默认 大小 2M  超过报错

    var form = new multiparty.Form({
        encoding:'utf-8',
        uploadDir: './public/tempup/'
    });
    form.parse(req, function(err, fields, files) {
        if (err){
            res.send("文件过大");
        }
        console.log(files.pic[0]);
        // { fieldName: 'pic',
        //     originalFilename: 'IMG_3129.JPG',
        //     path: 'public\\tempup\\exdmM5vxqQbLkqaB7agOOmy1.JPG',
        //     headers:
        //     { 'content-disposition': 'form-data; name="pic"; filename="IMG_3129.JPG"',
        //         'content-type': 'image/jpeg' },
        //     size: 4302872 }
        var size = parseInt(files.pic[0].size);
        var oldpath = files.pic[0].path;
        var originalFilename = files.pic[0].originalFilename;
        if(size > 2048*1024){
            res.send("图片尺寸应该小于2M");
            //删除图片
            fs.unlink(oldpath);
            return;
        }
        var random = parseInt(Math.random() * 89999 + 10000);
        // 获得文件后缀
        var extname = path.extname(originalFilename);
        //获得 表单 folder 参数
        var folder = fields.folder.toString();
        var newpath = path.normalize(__dirname + "/../uploads/" + folder + "/"  + random + extname);
        // 移动文件
        fs.rename(oldpath,newpath,function(err){
            if(err){
                console.log(err);
                res.send("改名失败");
                return;
            }
            res.send("成功");
        });
    });
    return;
});
module.exports = router;
